package com.ruoyi.web.controller.business;

import java.util.HashMap;
import java.util.Map;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.business.domain.WxUser;
import com.ruoyi.business.service.IWxUserService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.WxMiniProgramUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

/**
 * 微信小程序登录
 */
@RestController
@RequestMapping("/wx/miniapp")
public class WxMiniProgramController
{
    private static final Logger log = LoggerFactory.getLogger(WxMiniProgramController.class);

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private WxMiniProgramUtils wxMiniProgramUtils;

    /**
     * 微信小程序登录
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody Map<String, String> params)
    {
        try
        {
            if (!wxMiniProgramUtils.checkConfig())
            {
                return AjaxResult.error("系统配置错误，请联系管理员");
            }

            String code = params.get("code");
            if (StringUtils.isEmpty(code))
            {
                return AjaxResult.error("登录失败，code不能为空");
            }

            String openid = wxMiniProgramUtils.getOpenid(code);
            if (StringUtils.isEmpty(openid))
            {
                return AjaxResult.error("登录失败，获取openid失败");
            }

            // 获取用户信息（头像、昵称）
            String avatarUrl = params.get("avatarUrl");
            String nickName = params.get("nickName");
            
            log.info("接收到用户信息: openid={}, nickName={}, avatarUrl={}", openid, nickName, avatarUrl);

            WxUser wxUser = wxUserService.selectWxUserByOpenid(openid);
            if (wxUser == null)
            {
                // 新用户注册
                wxUser = new WxUser();
                wxUser.setOpenid(openid);
                wxUser.setStatus("0"); // 正常状态
                wxUser.setAvatar(avatarUrl);
                wxUser.setNickname(nickName);
                
                wxUserService.insertWxUser(wxUser);
                log.info("新微信用户注册成功，openid: {}", openid);
            }
            else
            {
                // 更新用户信息
                boolean needUpdate = false;
                
                // 更新头像
                if (StringUtils.isNotEmpty(avatarUrl) && !avatarUrl.equals(wxUser.getAvatar())) {
                    wxUser.setAvatar(avatarUrl);
                    needUpdate = true;
                }
                
                // 更新昵称
                if (StringUtils.isNotEmpty(nickName) && !nickName.equals(wxUser.getNickname())) {
                    wxUser.setNickname(nickName);
                    needUpdate = true;
                }
                
                if (needUpdate) {
                    wxUserService.updateWxUser(wxUser);
                    log.info("微信用户信息更新成功，openid: {}", openid);
                }
            }

            // 生成token
            LoginUser loginUser = (LoginUser) userDetailsService.loadUserByOpenid(openid);
            if (loginUser == null) {
                log.error("无法为 openid: {} 加载 LoginUser", openid);
                return AjaxResult.error("登录失败，用户认证信息加载失败");
            }
            
            String token = tokenService.createToken(loginUser);

            Map<String, Object> result = new HashMap<>();
            result.put(Constants.TOKEN, token);
            result.put("user", wxUserService.selectWxUserByOpenid(openid));
            return AjaxResult.success(result);
        }
        catch (Exception e)
        {
            log.error("微信小程序登录异常", e);
            return AjaxResult.error("登录失败，请稍后重试: " + e.getMessage());
        }
    }
    
    /**
     * 获取微信手机号
     */
    @PostMapping("/phone")
    public AjaxResult getPhoneNumber(@RequestBody Map<String, String> params, HttpServletRequest request)
    {
        try
        {
            String phoneCode = params.get("phoneCode");
            if (StringUtils.isEmpty(phoneCode))
            {
                return AjaxResult.error("获取手机号失败，phoneCode不能为空");
            }
            
            // 验证token
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (loginUser == null)
            {
                return AjaxResult.error("获取手机号失败，token无效");
            }
            
            // 获取手机号
            String phoneNumber = wxMiniProgramUtils.getPhoneNumber(phoneCode);
            if (StringUtils.isEmpty(phoneNumber))
            {
                return AjaxResult.error("获取手机号失败，请稍后重试");
            }
            
            // 更新用户手机号
            WxUser wxUser = wxUserService.selectWxUserByOpenid(loginUser.getUsername());
            if (wxUser != null)
            {
                wxUser.setPhone(phoneNumber);
                wxUserService.updateWxUser(wxUser);
                log.info("微信用户手机号更新成功，openid: {}, phone: {}", loginUser.getUsername(), phoneNumber);
            }
            
            Map<String, String> result = new HashMap<>();
            result.put("phoneNumber", phoneNumber);
            return AjaxResult.success(result);
        }
        catch (Exception e)
        {
            log.error("获取微信手机号异常", e);
            return AjaxResult.error("获取手机号失败，请稍后重试: " + e.getMessage());
        }
    }
}
